// pages/topic-end/topic-end.js
import { stopGlobalTimer } from '../../utils/timer';
import answerUtil from "../../utils/answerUtil";
import ajax from "../../utils/ajax";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    headerHidden:true,
    countdownTime: 60, // 倒计时时间
    submitState: null,//提交状态
  },

  onLoad(){
    this.onEnd();
  },
  
  onEnd(){
    const header = this.selectComponent('#header');
    header.stopTimer(); // 停止组件刷新
    stopGlobalTimer(); // 停止全局计时器
    
    const savedAnswerRecords = answerUtil.getAnswerRecords();
    const answerBaseData = wx.getStorageSync('answerBaseArray');

    // 添加answerBaseArray中的数据到答题数组中
    const totalRecords = savedAnswerRecords.map(item => {
      return {
        ...item,
        ...answerBaseData
      };
    });
    console.log('答题信息',totalRecords)
    // 提交答题信息
    ajax.postMethod('business/app/anwsers/wx/saveBatch', totalRecords).then(res => {
      console.log('提交答题信息',res)
      if (res.code === 200 || res.code === 230) {
        this.setData({
          submitState:true
        })
        // 页面进入倒计时
        this.startCountdown();
      }
      if(res.code !== 200){
        wx.showToast({
          title: res.msg,
          icon:'none'
        })
        this.setData({
          submitState:false
        })
      }
    }).catch(err => {
      console.error('答题信息提交失败', err);
    });
  },
  // 倒计时
  startCountdown() {
    // 清除已有倒计时
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
    }
    this.setData({
      countdownTime: 60
    });
    const interval = setInterval(() => {
      let newTime = this.data.countdownTime - 1;
      if (newTime > 0) {
        this.setData({
          countdownTime: newTime
        });
      } else {
        clearInterval(interval);
        // 倒计时结束，进入下一步
        wx.showToast({
          title: '进入下一步',
          icon: 'none',
          duration: 1000
        });
        setTimeout(() => {
          this.onStar();
        }, 1000);
      }
    }, 1000);
    this.setData({
      countdownInterval: interval
    });
  },
  onStar(){
    // 清除倒计时
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
      this.setData({ countdownInterval: null });
    }
    wx.reLaunch({
      url: '../topic-another/topic-another',
    })
  },
  onSubmit(){
    this.onEnd();
  },
  onUnload() {
    // 清除定时器
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
      this.setData({ countdownInterval: null });
    }
  }
})